import { Button, Form, Dialog, Input, Message } from '@alifd/next';
import { t } from '@lingui/macro';
import React, { useRef, useState, useEffect } from 'react';
import DrawerFooter from '@/components/DrawerFooter';
import { observable } from 'mobx';
import { observer } from 'mobx-react-lite';
import { useStore } from '@/hooks';
import { FieldsGrid } from '../stores/definitions';
import TauSimpleSelect from '@/components/TauSimpleSelect';

const formItemLayout = {
  labelCol: {
    fixedSpan: 8,
  },
  wrapperCol: {
    span: 16,
  },
  style: { marginBottom: 20 },
};

const NotifyForm = ({ notify, modal, onCancel, onSubmit, ...formProps }) => {
  const [formData] = useState(() => observable({}));
  const editCtx = useRef({ origin: {}, changed: {} }).current;
  const { notifyStore: store } = useStore();
  const [recipients, setRecipients] = useState([]);

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    (async () => {
      _.assign(formData, {});
      _.set(formData, 'sendType', 'day');
      _.set(formData, 'dayNumber', 1);
      _.set(formData, 'popupType', '1');
      _.set(formData, 'recipients', []);
    })();
  }, []);

  if (!formData) return <></>;

  const overrideModel = {
    recipients: {
      ui: {
        renderer: (v) => (
          <TauSimpleSelect value={v} mode="multiple" dataSource={recipients} />
        ),
      },
    },
    addRecipients: {
      ui: {
        renderer: () => (
          <Input
            placeholder="请输入手机号"
            addonAfter={<Button type="primary" onClick={handleAddUser}>{t`添加为接收者`}</Button>}
          />
        ),
      },
    },
  };

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(formData, name, value);
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleAddUser = async () => {
    const { addRecipients } = formData;
    if (!addRecipients) {
      return Message.warning({ content: t`请输入用户或者手机号!` });
    }
    const findUser = recipients?.find((p) => p.value.startsWith(addRecipients));
    if (findUser) {
      return Message.warning({ content: t`该用户已存在!` });
    }
    if (addRecipients === 'admin') {
      setRecipients((pre) => {
        const arr = [...pre];
        arr.push({ label: t`admin控制台`, value: 'admin@mzd' });
        return arr;
      });
      _.set(formData, 'recipients', formData.recipients.concat(['admin@mzd']));
      return;
    }
    try {
      const res = await store.getUserMobile(addRecipients);
      if (res) {
        setRecipients((pre) => {
          const arr = [...pre];
          arr.push({ label: res.fullname, value: res.username });
          return arr;
        });
        _.set(formData, 'recipients', formData.recipients.concat([res.username]));
      } else {
        Message.error({ content: t`该用户非平台用户!` });
      }
    } catch (error) {
      Message.error({ content: t`添加失败`, duration: 7000 });
      throw error;
    }
  };


  const handleSubmit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      console.log('...errors', errors);
      return;
    }
    const { type, businessKey, subject, content, sendTypes, popupType, sendType, period, weekdays, recipients: users } = formData || {};
    const params = {
      recipients: users,
    };
    params.notificationRequest = {
      type,
      businessKey,
      subject,
      content,
      sendTypes,
      params: {
        popupType,
        sendType,
        weekdays,
        period,
      },
    };
    onSubmit?.(params);
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <Form
      colon
      isPreview={false}
      {...formProps}
      value={formData}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <FieldsGrid
        formData={formData}
        itemLayout={{ ...formItemLayout, labelAlign: 'left' }}
        mode={modal[0]}
        columns={1}
        overrideModel={overrideModel}
        fields={['subject', 'type', 'sendTypes', 'popupType', 'sendType', 'addRecipients', 'recipients',
        ].concat(formData.sendType === 'day' ? ['period'] : ['weekdays'])
          .concat(['businessKey', 'content'])}
      />
      <DrawerFooter>
        <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>
        <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
      </DrawerFooter>
    </Form>
  );
};

export default observer(NotifyForm);
